// pages/index/mark-appraise/mark.js
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");
const util = require("../../../utils/util");
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null, // 老师信息
    date: null, // 选择的时间
    platePicker: [], // 板块数组
    plateIndex: 0, // 板块索引
    organizeList: [], // 年级班级列表
    showClazzList: [], // 展示的班级列表
    imgList: [], // 照片列表
    imgMaxLength: 4, // 照片最多张数（最大9）
    gradeCur: 0, // 当前选中的年级
    weekNo: 1, // 当前周
    weekStartDate: '2021-1-1', // 当前周开始日期
    weekEndDate: '2021-1-31', // 当前周结束日期
    nowDate: '', // 当前时间
    week: null, // 当前周日期
    scoreType: 'add', // add加分，sub扣分
    clazzString: '',
    clazzList: [], // 选择的年级班级数组，用于提交评分
    disabledPicUploadNum: 0,
    canChangeScore: false, // 身份是否可以加分扣分,
    isSubmit: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let weekNo = options.weekNo;
    let confId = options.confId;
    let week = options.weekStartDate.replaceAll('-', '.') + '-' + options.weekEndDate.replaceAll('-', '.')
    let userInfo = app.globalData.teacherInfo[0];
    let nowDate = util.formatDate(new Date());
    this.setData({
      weekNo: weekNo,
      confId: confId,
      isXz: options.isXz,
      weekStartDate: options.weekStartDate,
      weekEndDate: options.weekEndDate,
      nowDate: nowDate,
      date: nowDate,
      week,
      userInfo
    })
    this.setTeacherCharacter();
    this.setGradeClazzList();
    this.setPlateTypeList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.globalData.loadShow = true;
  },
  async setPlateTypeList() {
    let res = await requestUtil.request("GET", api.getDictData + 'eva_class', null);
    let platePicker = [];
    for(let i in res.data.data) {
      if(this.data.isXz == 1) {
        this.setData({
          plateIndex: i
        })
      }else {
        if(res.data.data[i].dictValue == '行政突击') {
          continue;
        }
      } 
      platePicker.push(res.data.data[i].dictValue);
    }
    this.setData({
      platePicker: platePicker
    })
  },
  /**
   * 设置年级班级列表
   */
  async setGradeClazzList() {
    let res = await requestUtil.request('GET', api.studentOrganize, {
      schoolId: app.globalData.teacherInfo[0].schoolId
    })
    if (res.data.code != 0) {
      wx.showToast({
        title: '获取班级失败，' + res.data.msg,
        icon: 'none'
      })
      return;
    }
    let data = res.data.data;
    let organizeList = [];
    for (let i = 0; i < data.length; i++) {
      for (let j = 0; j < data[i].subList.length; j++) {
        data[i].subList[j].selected = false;
      }
      let obj = {
        gradeName: data[i].gradeName,
        studyType: data[i].studyType,
        grade: data[i].grade,
        clazz: data[i].subList,
        hasChild: data[i].hasChild,
        selected: false, // 是否已被选上
      }
      organizeList.push(obj);
    }
    this.setData({
      organizeList: organizeList,
      showClazzList: organizeList[0].clazz,
    })
  },

  /**
   * 列表选择年级
   */
  chooseGrade(e) {
    this.setData({
      gradeCur: e.currentTarget.dataset.index,
      showClazzList: this.data.organizeList[e.currentTarget.dataset.index].clazz,
    })
  },

  /**
   * 年级checkbox的选择或取消
   */
  checkboxGrade(e) {
    let grade = e.currentTarget.dataset.id;
    for (let i = 0; i < this.data.organizeList.length; i++) {
      let organizeList = this.data.organizeList;
      if (grade == organizeList[i].grade) {
        organizeList[i].selected = !organizeList[i].selected;
        // 也把每个班的selected选上（取消）
        for (let j = 0; j < organizeList[i].clazz.length; j++) {
          organizeList[i].clazz[j].selected = organizeList[i].selected;
        }
        // 如果是当前选择年级的checkbox改变，则同时改变右侧
        if (organizeList[i].grade == organizeList[this.data.gradeCur].grade) {
          this.setData({
            organizeList: organizeList,
            showClazzList: organizeList[i].clazz
          });
        } else {
          this.setData({
            organizeList: organizeList,
          });
        }
        break;
      }
    }
    // this.setClazzString();
  },

  checkboxClazz: function (e) {
    let clazz = e.currentTarget.dataset.id;
    let clazzList = this.data.organizeList[this.data.gradeCur].clazz;
    for (let i = 0; i < clazzList.length; i++) {
      if (clazzList[i].clazz == clazz) {
        clazzList[i].selected = !clazzList[i].selected;
        break;
      }
    }
    // this.setClazzString();
  },

  /**
   * 选择日期触发
   */
  DateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  /**
   * 选择照片
   */
  ChooseImage() {
    app.globalData.loadShow = false; // 先禁用chooseImage和uploadFile导致调用app.onShow
    wx.chooseImage({
      count: this.data.imgMaxLength, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择或拍照
      success: (res) => {
        let tempFilePaths = res.tempFilePaths;
        // if (this.data.imgList.length != 0) {
        //   this.setData({
        //     imgList: this.data.imgList.concat(tempFilePaths)
        //   })
        // } else {
        //   this.setData({
        //     imgList: tempFilePaths
        //   })
        // }
        let teacherId = app.globalData.teacherInfo[0].id;
        for (let i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            filePath: tempFilePaths[i],
            name: 'file',
            url: api.addAttch,
            header: {
              'content-type': 'multipart/form-data',
              'xcx-token': getApp().xcxtoken
            },
            formData: {
              'attachType': 'image',
              'operatorId': teacherId,
              'relationType': 'evaClass'
            },
            success: res => {
              app.globalData.loadShow = true;
              let resData = JSON.parse(res.data);
              if (resData.code == 0) {
                let imgList = this.data.imgList;
                let data = resData.data;
                let obj = {
                  id: data.id,
                  attachUrl: data.attachUrl,
                  tempFilePath: tempFilePaths[i],
                  attachType: data.attachType,
                  operatorId: data.operatorId
                }
                imgList.push(obj);
                this.setData({
                  imgList: imgList
                })
              }
            },
            fail: err => {
              console.error('Upload File fail, reason is :', err);
            }
          })
        }
      }
    });
  },

  /**
   * 预览图片
   */
  ViewImage(e) {
    app.globalData.loadShow = false; // 先禁用chooseImage和uploadFile导致调用app.onShow
    let imgList = this.data.imgList;
    let urls = [];
    for (let i of imgList) {
      urls.push(i.tempFilePath);
    }
    wx.previewImage({
      urls: urls,
      current: e.currentTarget.dataset.url
    });
  },

  /**
   * 显示Modal
   */
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },

  /**
   * 隐藏Modal
   */
  hideModal() {
    this.setClazzString();
    this.setData({
      modalName: null
    })
  },

  /**
   * 设置班级显示的字符串
   */
  setClazzString() {
    let organizeList = this.data.organizeList;
    let str = '';
    let selectedClazzList = [];
    let disabledPicUploadNum = 0; // 如果这个数大于1就代表多选班级，禁止图片上传
    for (let i = 0; i < organizeList.length; i++) {
      let clazzList = organizeList[i].clazz;
      for (let j = 0; j < clazzList.length; j++) {
        if (clazzList[j].selected) {
          str += organizeList[i].gradeName + clazzList[j].clazz + '班' + ',';
          disabledPicUploadNum++;
          selectedClazzList.push({
            gradeName: organizeList[i].gradeName,
            clazz: clazzList[j].clazz
          });
        }
      }
    }
    this.setData({
      clazzString: str.length > 0 ? str.substring(0,str.length - 1) : str,
      disabledPicUploadNum: disabledPicUploadNum,
      clazzList: selectedClazzList
    })
  },

  /**
   * 加扣分单选框变更
   */
  ChangeScoreRadio(e) {
    this.setData({
      scoreType: e.detail.value
    })
  },

  /**
   * 表单确认
   */
  formSubmit(e) {
    let formData = e.detail.value;
    let scoreType = this.data.scoreType;
    let score = Number(formData.score);
    if(score == 0) {
      wx.showToast({
        title: '分数不能为0',
        icon: 'none'
      });
      return;
    }
    if (scoreType == 'sub') {
      formData.score = (score < 0 ? score : 0 - score);
    }else {
      formData.score = (score < 0 ? 0 - score : score);
    }
    formData.confId = Number(this.data.confId);
    formData.plateType = this.data.platePicker[this.data.plateIndex];
    formData.regTeacherId = Number(this.data.userInfo.id);
    formData.schoolId = Number(this.data.userInfo.schoolId);
    formData.marker = null;
    formData.date = null;

    if (this.data.clazzList.length == 0) {
      wx.showToast({
        title: '请先选择班级',
        icon: 'none'
      });
      return;
    } else if (this.data.clazzList.length == 1) {
      formData.gradeName = this.data.clazzList[0].gradeName;
      formData.clazz = this.data.clazzList[0].clazz;
    } else if (this.data.clazzList.length > 1) {
      formData.clazzList = this.data.clazzList
    }
    this.postForm(formData);
  },

  /**
   * 提交表单
   */
  async postForm(formData) {
    if(this.data.isSubmit) return;
    this.setData({
      isSubmit: true
    })
    let res = await requestUtil.request('POST', api.submitReg, formData);
    if (res.data.code == 0) {
      wx.showToast({
        title: '提交成功'
      });
      setTimeout(function () {
        wx.navigateBack({
          delta: 1,
        })
      }, 2000)
    } else {
      console.log("111", res.data);
      wx.showToast({
        title: '提交失败，原因为：' + res.data.msg,
        icon: 'none'
      })
      this.setData({
        isSubmit: false
      })
    }
  },

  /**
   * 板块选择
   */
  platePickerChange(e) {
    this.setData({
      plateIndex: e.detail.value
    })
  },

  /**
   * 删除照片
   */
  delImg(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '删除照片',
      content: '确认删除照片吗？',
      async success(res) {
        if (res.confirm) {
          // 本地删除图片
          let imgList = _this.data.imgList;
          let imgInfo = imgList[index];
          imgList.splice(index, 1);
          _this.setData({
            imgList: imgList
          });
          let res = await requestUtil.request("POST", api.delAttach, {
            id: imgInfo.id
          });
          if (res.data.code == 0) {
            wx.showToast({
              title: '删除成功',
            })
          }
        } else if (res.cancel) {
          console.log('取消')
          //TODO
        }
      }
    })
  },

  /**
   * 禁止选择图片
   */
  banChoosePic() {
    wx.showToast({
      title: '未选或多选班级时禁止上传图片',
      icon: 'none'
    })
  },

  /**
   * 设置老师身份
   */
  setTeacherCharacter() {
    let _this = this;
    let characterObj = app.globalData.teacherCharacter;
    if (characterObj.isHead || characterObj.isLeader || characterObj.evaLeaderType != 0) {
      _this.setData({
        canChangeScore: true
      });
    } else {
      _this.setData({
        canChangeScore: false
      });
    }
  },
})